package com.xuyuan.spring.transaction;

import com.xuyuan.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class EventTransactionManager {

    static final Logger logger = LoggerFactory.getLogger(EventTransactionManager.class);
    static final String DEFAULT_TRANSACTION = "_BUSINESS_EVENT_PROCESSING";
    private PlatformTransactionManager manager;


    public EventTransactionManager() {
        manager = SpringUtil.getBean(PlatformTransactionManager.class);
    }


    public TransactionStatus getTransaction(TransactionDefinition transactionDefinition) {
        return manager.getTransaction(transactionDefinition);
    }


    public TransactionStatus begin() {
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setName(DEFAULT_TRANSACTION);
        transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        transactionDefinition.setTimeout(20 * 60);
        return manager.getTransaction(transactionDefinition);
    }


    public void rollback(TransactionStatus transactionStatus) {
        manager.rollback(transactionStatus);
    }


    public void commit(TransactionStatus transactionStatus) {
        manager.commit(transactionStatus);
    }

}